import 'dart:io' show File;

import 'package:chewie/chewie.dart';
import 'package:flutter/material.dart';
import 'package:flutter_app/r.dart';
import 'package:flutter_app/widget/image_watermark.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:photo_view/photo_view.dart';
import 'package:video_player/video_player.dart';

import 'model.dart';

export 'model.dart';

void gallery(List<GalleryModel> items, {int showIndex = 0}) {
  Get.to(
    () => GalleryPage(
      items: items,
      showIndex: showIndex,
    ),
    transition: Transition.noTransition,
  );
}

class GalleryPage extends StatefulWidget {
  final List<GalleryModel> items;
  final int showIndex;
  late PageController pageCtrl;

  GalleryPage({
    Key? key,
    required this.items,
    required this.showIndex,
  }) : super(key: key) {
    pageCtrl = PageController(initialPage: showIndex);
  }

  @override
  _GalleryPageState createState() {
    return _GalleryPageState();
  }
}

class _GalleryPageState extends State<GalleryPage> {
  late RxInt currentIndex = (widget.showIndex + 1).obs;

  final List<Widget> widgets = [];

  @override
  void initState() {
    super.initState();
    setWidget();
  }

  List<Widget> setWidget() {
    widget.items.forEach((element) {
      if (element.url.contains('jpeg') ||
          element.url.contains('jpg') ||
          element.url.contains('png')) {
        widgets.add(PhotosView(element));
      } else {
        widgets.add(VideosView(galleryModel: element));
      }
    });
    return widgets;
  }

  void onPageChanged(int index) {
    currentIndex.value = (index + 1);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.black,
      appBar: AppBar(
        elevation: 1,
        backgroundColor: Colors.transparent,
        leading: IconButton(
          onPressed: () {
            Navigator.maybePop(context);
          },
          tooltip: MaterialLocalizations.of(context).backButtonTooltip,
          icon: Image.asset(R.assetsImgIcon4_1, width: 30.r),
        ),
      ),
      body: Stack(
        children: [
          PageView(
            controller: PageController(initialPage: widget.showIndex),
            children: widgets,
            onPageChanged: onPageChanged,
          ),
          Align(
            alignment: Alignment.bottomCenter,
            child: Container(
              padding: EdgeInsets.all(20.0.r),
              child: Obx(() {
                return Text(
                  "$currentIndex / ${widget.items.length}",
                  style: TextStyle(
                    color: Colors.white,
                    fontSize: 17.0.sp,
                    decoration: null,
                  ),
                );
              }),
            ),
          ),
        ],
      ),
    );
  }

  @override
  void dispose() {
    super.dispose();
  }
}

///=============================================================================================================
// 图片
Widget PhotosView(GalleryModel item) {
  var imageProvider;
  if (item.url.startsWith("http")) {
    imageProvider = NetworkImage(item.url);
  } else {
    imageProvider = FileImage(File(item.url));
  }
  return PhotoView(
    imageProvider: imageProvider,
    onTapUp: (BuildContext context, details, controllerValue) {
      Navigator.pop(context);
    },
  );
}

///=============================================================================================================
// 视频播放页面
class VideosView extends StatefulWidget {
  final GalleryModel galleryModel;

  VideosView({Key? key, required this.galleryModel}) : super(key: key);

  @override
  _VideosViewState createState() {
    return _VideosViewState();
  }
}

class _VideosViewState extends State<VideosView> {
  ///创建视频播放控制 器
  late VideoPlayerController videoPlayerController;
  /// 创建chewie Controller
  late ChewieController chewieController;
  ///控制更新视频加载初始化完成状态更新
  late Future videoPlayFuture;

  late bool showImageWatermark = false;

  @override
  void initState() {
    super.initState();
    if (widget.galleryModel.time != null &&
        widget.galleryModel.address != null) {
      showImageWatermark = true;
    }

    String url = widget.galleryModel.url;
    if (url.startsWith("http")) {
      videoPlayerController = VideoPlayerController.network(url);
    } else {
      videoPlayerController = VideoPlayerController.file(File(url));
    }

    videoPlayerController.initialize().then((_) {
      chewieController = ChewieController(
        // 播放速度设置
        optionsTranslation: OptionsTranslation(cancelButtonText: "取消", playbackSpeedButtonText: "倍速"),
        videoPlayerController: videoPlayerController,
        // 屏幕高宽比
        aspectRatio: videoPlayerController.value.aspectRatio,
        // 允许屏幕睡眠
        allowedScreenSleep: false,
        // 进度条颜色
        materialProgressColors: ChewieProgressColors(
          playedColor: Colors.white,
          bufferedColor: Colors.white60,
          handleColor: Colors.white,
        ),
        cupertinoProgressColors: ChewieProgressColors(
          playedColor: Colors.white,
          bufferedColor: Colors.white60,
          handleColor: Colors.white,
        ),
        // 自动播放
        autoPlay: true,
        // 循环
        looping: false,
      );

      setState(() {});
    });
  }

  @override
  void dispose() {
    super.dispose();
    videoPlayerController.dispose();
    chewieController.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.black,
      body: SafeArea(
        child: Center(
          child: videoPlayerController.value.isInitialized
              ? Stack(
                children: [
                  Container(
                    width: 1.sw,
                    height: 1.sw / videoPlayerController.value.aspectRatio,
                    child: Chewie(controller: chewieController),
                  ),
                  // 本身和子组件都不能接收点击事件
                  IgnorePointer(
                    child: Visibility(
                      visible: showImageWatermark,
                      child: Container(
                        margin: EdgeInsets.only(top: 8.r, left: 8.r),
                        child: ImageWatermark(
                          fontSize: 8.sp,
                          time: widget.galleryModel.time,
                          name: widget.galleryModel.photographer,
                          address: widget.galleryModel.address ?? "",
                        ),
                      ),
                    ),
                  ),
                ],
              )
              : CircularProgressIndicator(color: Colors.white),
        ),
      ),
    );
  }
}
